package com.fanrenqiji.wechat.handler;


import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 
 * @author Binary Wang
 *
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
            Map<String, Object> context, WxMpService weixinService,
            WxSessionManager sessionManager)    {

        if (!wxMessage.getMsgType().equals(WxConsts.XML_MSG_EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                && weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
                WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
                article1.setDescription("客服回复内容");
                article1.setTitle("客服回复");
                article1.setUrl("http://www.baidu.com");

                WxMpKefuMessage message  = WxMpKefuMessage
                        .NEWS()
                        .toUser(wxMessage.getFromUser())
                        .addArticle(article1)
                        .build();
                weixinService.getKefuService().sendKefuMessage(message);
                return null;
                /*return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser()).build();*/
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
        article1.setDescription("客服回复内容");
        article1.setTitle("客服回复");
        article1.setUrl("http://www.baidu.com");

        WxMpKefuMessage message  = WxMpKefuMessage
                .NEWS()
                .toUser(wxMessage.getFromUser())
                .addArticle(article1)
                .build();
        try {
            weixinService.getKefuService().sendKefuMessage(message);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;

       /* //TODO 组装回复消息
        String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);

        return new TextBuilder().build(content, wxMessage, weixinService);*/

    }

}
